-- 引入redis
local redis = require('resty.redis');
-- 初始化redis
local red = redis:new();
red:set_timeouts(5000, 5000, 5000);

-- 设置全局变量
redis_ip = "192.168.30.152";
redis_port = 6379;

-- 连接池，优雅关闭redis连接 有方法顺序问题 如果设置全局方法需要去掉local修饰
local function do_gracefully_redis_pool(redis) 

    -- redis 如果存在则不要继续向下执行
    if not redis then 
        return;
    end

    -- 连接的最大空闲时间，单位ms，时间单位内redis不会关闭，如果空闲则关闭
    local pool_max_idel_time = 15000; 
    -- 连接池大小
    local pool_size = 50; 
    -- 设定连接池参数
    local ok, err = redis:set_keepalive(pool_max_idel_time, pool_size);

    if not ok then
        ngx.log(ngx.ERR, "failed to set keepalive: ", err)
        return;
    end
end


-- 从redis中查询数据
local function get_data(key)
    -- 建立连接
    local ok, err = red:connect(redis_ip, redis_port);
    if not ok then
        ngx.log(ngx.ERR, "failed to connect: ", err)
        return
    end

    local res, err = red:auth("SbtyMveYNfLzTks7H0apCmyStPzWJqjy")
    if not res then
        ngx.log(ngx.ERR, "failed to authenticate: ", err)
        return
    end

    -- 查询redis
    local res, err = red:get(key)
    do_gracefully_redis_pool(red);
    return res;
end

-- 在redis中设置数据
local function set_data(key, value)
    -- 建立连接
    local ok, err = red:connect(redis_ip, redis_port);
    if not ok then
        ngx.log(ngx.ERR, "failed to connect: ", err)
        return
    end

    local res, err = red:auth("SbtyMveYNfLzTks7H0apCmyStPzWJqjy")
    if not res then
        ngx.log(ngx.ERR, "failed to authenticate: ", err)
        return
    end

    --  设值
    ok, err = red:set(key, value);
    ok, err = red:expire(key, 1500);

    do_gracefully_redis_pool(red);
end






-- 导出函数
local _M = {
    get_data = get_data,
    set_data = set_data
}
return _M;
